package com.neuqsoft.ymtdemo.view;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.neuqsoft.ymtdemo.App;
import com.neuqsoft.ymtdemo.R;
import com.neuqsoft.ymtdemo.bean.MoudleBean;
import com.neuqsoft.ymtdemo.utils.RequestUtil;
import com.neuqsoft.ymtdemo.utils.SPUtils;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.HashMap;
import java.util.Map;

import essclib.pingan.ai.request.biap.Biap;
import essclib.pingan.ai.request.biap.common.ApiConstants;
import essclib.pingan.ai.request.biap.net.LogUtils;
import hc.mhis.paic.com.essclibrary.EsscSDK;
import hc.mhis.paic.com.essclibrary.listener.ESSCCallBack;

/**
 * <pre>
 *     author : wulh
 *     e-mail : wulh@neuqsoft.com
 *     time   : 2020/03/17
 *     desc   :Demo主页
 *     version: 1.0
 * </pre>
 */

public class FunctionActivity extends AppCompatActivity implements ESSCCallBack {
    private EditText minput_address;
    private static final String def_url = "https://service.neuqsoft.com/ggfw/citizen/login";
    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            String url = (String) msg.obj;
            //sdk拉起登录方法，传入签发回调的地址，注意需在主线程操作
            EsscSDK.getInstance().startSdk(FunctionActivity.this,
                    Biap.getInstance().getImpowerLogin() + "?" + url, FunctionActivity.this);
            return false;
        }
    });
    private SPUtils spUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
        setContentView(R.layout.activity_function);
//        mtv_title = findViewById(R.id.tv_title);
        minput_address = findViewById(R.id.input_address);
        spUtils = new SPUtils(this, "URLPATH");
        String urlpath = spUtils.getString("urlpath");
        boolean clearUrl = spUtils.getBoolean("clearUrl");
        if (!clearUrl) {
            minput_address.setText(def_url);
            saveUrlPath(def_url);
        } else {
            if (!TextUtils.isEmpty(urlpath)) {
                minput_address.setText(urlpath);
            } else {
                minput_address.setText(def_url);
            }
        }
        EsscSDK.init(App.getApp(), ApiConstants.URL_TEST);
        App.accessKey = "3e3cbf23be4c4c7baf01436f370099f2";
        App.channelNo = "2000000000";
        App.environmentUrl = ApiConstants.URL_TEST;
        spUtils.putBoolean("clearUrl", true);
    }

    @Override
    public void onESSCResult(String data) {
        //TODO SDK回调结果
        Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
        LogUtils.e("result", data);
        //此处为方便测试，保存用户信息到本地
        MoudleBean bean = JSONObject.parseObject(data, MoudleBean.class);
        //模拟解绑操作
        if (!TextUtils.isEmpty(bean.getActionType()) && bean.getActionType().equals("003")) {

            App.signNO = "";

            App.aab301 = "";

            App.aac002 = "";

            App.aac003 = "";

            App.token = "";

            Map map = new HashMap();
            map.put("channelNo", App.channelNo);
            if (!TextUtils.isEmpty(bean.getAab301())) {
                map.put("aab301", bean.getAab301());
            }
            map.put("aac002", bean.getAac002());
            map.put("aac003", bean.getAac003());
            map.put("signNo", bean.getSignNo());
            map.put("idcard", bean.getAac002());
            map.put("username", bean.getAac003());
            map.put("actionType", bean.getActionType());
            map.put("signDate", bean.getSignDate());
            map.put("signLevel", bean.getSignLevel());
            map.put("signSeq", "");
            map.put("validDate", bean.getValidDate());

            RequestUtil.potApply(JSONObject.toJSONString(map), new RequestUtil.CallBackNet() {

                @Override
                public void onSuccess(String data) {

                }

                @Override
                public void onFail(String data) {

                }
            });
        }

        //到卡面记录信息，模拟渠道记录操作
        if (!TextUtils.isEmpty(bean.getActionType()) && bean.getActionType().equals("006")) {

            if (!TextUtils.isEmpty(bean.getSignNo())) {
                App.signNO = bean.getSignNo();
            }
            if (!TextUtils.isEmpty(bean.getAab301())) {
                App.aab301 = bean.getAab301();
            }
            if (!TextUtils.isEmpty(bean.getAac002())) {
                App.aac002 = bean.getAac002();
            }
            if (!TextUtils.isEmpty(bean.getAac003())) {
                App.aac003 = bean.getAac003();
            }
            if (!TextUtils.isEmpty(bean.getToken())) {
                App.token = bean.getToken();
            }
        }

        if (!TextUtils.isEmpty(bean.getActionType()) && bean.getActionType().equals("022")) {
            EsscSDK.getInstance().closeSDK();//关闭esscsdk
            //用拿到的信息去做app登录操作
            Intent intent = new Intent(this, YouAppHomeActivity.class);
            startActivity(intent);
            Toast.makeText(getApplicationContext(), "登陆成功！", Toast.LENGTH_LONG).show();
            EsscSDK.getInstance().closeSDK();
        }
    }





    /**
     * 在电子社保卡载体APP（如人社APP)已登录的情况下。第三方APP中选择用电子社保卡载体APP登录，
     * 用户授权确认后，拉起人社APP获取到当前用户电子社保卡信息，从而获得参保人信息，并在第三方APP中完成登录
     */

    public void startLogin(View v) {//第三方APP调用电子社保卡部平台登录
        RequestUtil.sign("", "", "", new RequestUtil.CallBackNet() {
            @Override
            public void onSuccess(String data) {
                Message message = new Message();
                message.obj = data;
                mHandler.sendMessageDelayed(message, 3000);
            }

            @Override
            public void onFail(String data) {

            }
        });
    }


    public void startH5(View v) {  // H5电子社保卡接入
        if (!TextUtils.isEmpty(minput_address.getText())) {
            saveUrlPath(minput_address.getText().toString());
            Intent intent = new Intent(this, WebViewEsscH5Activity.class);
            intent.putExtra("direurl", minput_address.getText().toString());
            startActivity(intent);
        } else {
            Toast.makeText(this, "地址不能为空！", Toast.LENGTH_LONG).show();
        }
    }

    public void showTips(View v) {  // 弹出提示信息
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.edit_tip));
        builder.setPositiveButton("知道了", null);
        builder.show();
    }

    public void saveUrl(View v) {  // 更新
        saveUrlPath(minput_address.getText().toString());
        Toast.makeText(this, "更新成功！", Toast.LENGTH_SHORT).show();
    }

    private void saveUrlPath(String path) {
        spUtils.putString("urlpath", path);
    }

    public void startScan(View v) {  // 扫码获取网址

        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent, 1);

    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    minput_address.setText(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
